var express = require('express');
var router = express.Router();
var filmsService = require('../service/filmsService')

//查询所有
router.get('/', async function (req, res, next) {
    console.log('/');
    let { type, value, current, size, flag } = req.query;
    let searchObj = {};
    //模糊查询
    if (type && value) {
        if (type == 'score' || type == 'status' || flag) {
            searchObj[type] = value;
        } else {
            searchObj[type] = { $regex: value };
        }
    }
    let data = await filmsService.find(searchObj, { current: current || 1, size: size || 3 });
    res.send(data);
})

//查询所有  热播  hotBroadcast 热映  hotBroadcast 待映
router.get('/all', async function (req, res, next) {

    console.log(123);
    let { current, size, } = req.query;
    let data = await filmsService.findAll({ current: current || 10, size: size || 3 });
    res.send(data);
})


//添加电影
router.post('/', async function (req, res, next) {
    if (req.body.director) {
        req.body.director = JSON.parse(req.body.director);
    }
    if (req.body.actor) {
        req.body.actor = JSON.parse(req.body.actor);
    }
    let data = await filmsService.insert(req.body);
    res.send(data)
})

//删除电影
router.delete('/:id', async function (req, res, next) {
    let id = req.params.id;
    let data = await filmsService.delete(id);
    res.send(data)
})

//修改电影
router.put('/:id', async function (req, res, next) {
    let id = req.params.id;
    if (req.body.director) {
        req.body.director = JSON.parse(req.body.director);
    }
    if (req.body.actor) {
        req.body.actor = JSON.parse(req.body.actor);
    }
    let data = await filmsService.update(id, req.body);
    res.send(data)
})

//根据ID查询
router.get('/:id', async function (req, res, next) {
    console.log('id');
    let id = req.params.id;
    let data = await filmsService.findById(id);
    res.send(data);

})

//查询前十名
router.get('/sort/all',async function(req,res,next){
    let data =await filmsService.findSort();
    res.send(data);
})

module.exports = router;